<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/轮播图.css">
    <script src="../js/轮播图.js"></script>
</head>
<body>
    <div id="carousel">
        <ul id="carousel2">
            <li><img src="../img/轮播图1.jpg" alt=""></li>
            <li><img src="../img/轮播图2.jpg" alt=""></li>
            <li><img src="../img/轮播图3.jpg" alt=""></li>
            <li><img src="../img/轮播图4.jpg" alt=""></li>
            <li><img src="../img/轮播图1.jpg" alt=""></li>
        </ul>
        <ul id="icolist">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
        <div class="prev"><</div>
        <div class="next">></div>
    </div>
    <script>
        var eprev = document.querySelector('.prev');
        var enext = document.querySelector('.next');
        var esico = document.getElementById('icolist').getElementsByTagName('li');
        var eicolist = document.querySelector('#icolist');
        var eimglist = document.querySelector('#imglist');
        var left = 0; // 左侧的位置
        var timer; 
        run(); // 调用run()函数
        function run() {
            if(left<=-3200){
                left=0; // 左侧的位置归零
            }
        var m=Math.floor(-left/800); // 当前图片的索引
        carousel2.style.marginLeft =left +"px"; // 设置左侧的位置
        var n=(left%800==0)?n=1200:n=10; // 定时器的间隔时间
        left -= 10; // 左侧的位置减少10
        timer=setTimeout(run, n); // 定时器，每隔20毫秒执行一次run()函数
        icochange(m); // 调用icochange()函数，显示当前图片的索引
        }
        function imgchange(n) {
            let lt = - (n*800);
            carousel2.style.marginLeft = lt + "px";
            left = lt;
        }
        eprev.onclick = function() {
            let prev=Math.floor(-left/800)-1;
            if(prev==-1){
                prev=3;
            }
            imgchange(prev);
        }
        enext.onclick = function() {
            let next=Math.floor(-left/800)+1;
            if(next==4){
                next=0;
            }
            imgchange(next);
        }
        function icochange(m) {
            for (let index = 0; index <esico.length; index++) {
                esico[index].style.backgroundColor ='';
            }
            if(m<esico.length){
                esico[m].style.backgroundColor = 'red';
            }
        }
        eicolist.onclick = function() {
            var tg=event.target;
            let ico=tg.innerHTML-1;
            imgchange(ico);
            icochange(ico);
        }
        eimglist.onmouseover = function() {
            clearTimeout(timer);
        }
        eimglist.onmouseout = function() {
            run();
        }
    </script>
</body>
</html>